import json
import re
from typing import List

class DataFormatter:
    """数据格式化工具类"""
    
    @staticmethod
    def format_ball_number(num) -> str:
        """格式化球号为两位数"""
        if num is None or num == '' or (isinstance(num, (int, float)) and (num != num)):  # 检查NaN
            return '00'
        return str(num).zfill(2)
    
    @staticmethod
    def format_prize_info(prize_info: str) -> str:
        """格式化奖金信息"""
        if not prize_info:
            return ''
        
        try:
            prize_data = json.loads(prize_info)
            formatted_html = '<div class="prize-list">'
            
            if isinstance(prize_data, list):
                for prize in prize_data:
                    if isinstance(prize, dict) and prize.get('type') and prize.get('typenum') and prize.get('typemoney'):
                        prize_names = {
                            1: '一等奖', 2: '二等奖', 3: '三等奖',
                            4: '四等奖', 5: '五等奖', 6: '六等奖'
                        }
                        prize_name = prize_names.get(prize['type'], f'{prize["type"]}等奖')
                        
                        if prize['typenum'] > 0:
                            formatted_html += f'''
                                <div class="prize-item">
                                    <span class="prize-name">{prize_name}：</span>
                                    <span class="prize-count">{prize['typenum']}注</span>
                                    <span class="prize-money">单注¥{prize['typemoney']}</span>
                                </div>
                            '''
            
            formatted_html += '</div>'
            return formatted_html
            
        except Exception:
            return f'<pre class="prize-text">{prize_info}</pre>'
    
    @staticmethod
    def format_analysis_text(text: str) -> str:
        """格式化分析文本"""
        if not text:
            return ''
        
        # 替换标题格式
        text = re.sub(r'###\s*(.*?)[:：]', r'\n\n🎯 \1：', text)
        text = re.sub(r'####\s*(.*?)[:：]', r'\n\n📊 \1：', text)
        text = re.sub(r'\*\*(.*?)\*\*', r'▶ \1', text)
        
        # 处理主要章节
        text = re.sub(r'预测号码[:：]', r'\n\n🎲 预测号码：', text)
        text = re.sub(r'分析说明[:：]', r'\n\n📈 分析说明：', text)
        text = re.sub(r'分析依据[:：]', r'\n\n📋 分析依据：', text)
        text = re.sub(r'杀号分析[:：]', r'\n\n❌ 杀号分析：', text)
        text = re.sub(r'选号分析[:：]', r'\n\n✅ 选号分析：', text)
        
        # 处理预测号码格式
        text = re.sub(r'🔴\s*第(\d+)组[:：]?\s*\[([^\]]+)\]\s*,?\s*🔵\s*蓝球\s*(\d+)', r'\n  第\1组：🔴 【\2】 🔵 蓝球\3', text)
        text = re.sub(r'第(\d+)组[:：]?\s*\[([^\]]+)\]\s*,?\s*蓝球\s*(\d+)', r'\n  第\1组：🔴 【\2】 🔵 蓝球\3', text)
        
        # 处理红球蓝球信息
        text = re.sub(r'红球\[([^\]]+)\]', r'🔴 【\1】', text)
        text = re.sub(r'蓝球\s*(\d+)', r' 🔵 蓝球\1', text)
        text = re.sub(r'红球(\d+)', r'🔴 红球\1', text)
        
        # 处理概率和成功率信息
        text = re.sub(r'成功率[:：]?\s*约?(\d+%)', r'📊 成功率: \1', text)
        text = re.sub(r'概率[:：]?\s*约?(\d+%)', r'📊 概率: \1', text)
        text = re.sub(r'出现\d+次', lambda m: f'📈 {m.group()}', text)
        
        # 处理分割线
        text = re.sub(r'[-─]{3,}', '\n' + '─' * 50 + '\n', text)
        text = re.sub(r'\*{3,}', '★' * 3, text)
        
        # 处理列表项
        text = re.sub(r'^\s*[-•]\s+', '  • ', text, flags=re.MULTILINE)
        text = re.sub(r'^(\d+)[\.、]\s*', r'\1. ', text, flags=re.MULTILINE)
        
        # 处理数字范围和特殊格式
        text = re.sub(r'\[([^\]]+)\]', r'【\1】', text)
        text = re.sub(r'\(([^)]+)\)', r'（\1）', text)
        
        # 清理格式
        text = re.sub(r'\n{3,}', '\n\n', text)
        text = text.strip()
        
        return text
